package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.contast.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.sun.jersey.core.impl.provider.entity.ReaderProvider;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.ibatis.io.ResolverUtil;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Gallant
 * @create 2020-07-11 19:31
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    // 会员汇总
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        try {
            // 创建一个map用户封装数据
            Map map = new HashMap();
            // 获取年月,添加到list集合,然后再将list集合put到map中
            // 1.先求出当前月份往前推12个月份
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH,-24);
            // 2.然后来一个循环将每个月份装到一个list集合中
            List<String> months = new ArrayList<>();
            List<Integer> memberCount = new ArrayList<>();

            for (int i = 0; i < 24; i++) {
                calendar.add(Calendar.MONTH,1);
                String month = new SimpleDateFormat("yyyy.MM").format(calendar.getTime());
                months.add(month);
                // 根据月份查询会员的count
                Integer count = memberService.findMemberCountByMonth(month);
                memberCount.add(count);
            }
            map.put("months",months);
            map.put("memberCount",memberCount);
            return new Result(true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    // 套餐汇总
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        try {
            // 封装数据,返回给前端就行了
            Map<String,Object> map = new HashMap<>();

            // 通过setmealDao将套餐统计信息查询出来
            List<Map<String, Object>> setmealCount = setmealService.findSetmealCount();
            // 创建一个List集合用于封装套餐名称信息
            List<String> setmealNames = new ArrayList<>();
            // 对套餐统计信息进行遍历
            for (Map<String, Object> stringObjectMap : setmealCount) {
                // 从套餐统计信息中获取套餐名称,添加到list集合中
                setmealNames.add((String) stringObjectMap.get("name"));
            }
            // 将数据用map进行封装
            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealCount);
            // 将数据返回给前台
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    // 会员性别
    @RequestMapping("/getGenderReport")
    public Result getGenderReport(){
        try {
            // 封装数据,返回给前端就行了
            Map<String,Object> map = new HashMap<>();

            // 通过setmealDao将性别统计信息查询出来
            List<Map<String, Object>> memberGenderCount = memberService.findMemberGenderCount();
            // 创建一个List集合用于封装性别名称信息
            List<String> memberGenderNames = new ArrayList<>();
            // 对性别统计信息进行遍历
            for (Map<String, Object> stringObjectMap : memberGenderCount) {
                // 从性别统计信息中获取套餐名称,添加到list集合中
                memberGenderNames.add((String) stringObjectMap.get("name"));
            }
            // 将数据用map进行封装
            map.put("setmealNames",memberGenderNames);
            map.put("setmealCount",memberGenderCount);
            // 将数据返回给前台
            return new Result(true,MessageConstant.GET_MEMBER_GENDER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_GENDER_REPORT_FAIL);
        }
    }

    // 会员年龄
    @RequestMapping("/getAgeReport")
    public Result getAgeReport(){
        try {
            // 通过setmealDao将年龄统计信息查询出来
            Map<String, Object> memberAgeCount = memberService.findMemberAgeCount();
            // 将数据返回给前台
            return new Result(true,MessageConstant.GET_MEMBER_Age_REPORT_SUCCESS,memberAgeCount);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_MEMBER_Age_REPORT_FAIL);
        }
    }

    @Reference
    private ReportService reportService;
    // 运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            // 从数据库中查询出想要的数据
            Map<String, Object> data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();
            // 将运营数据写到表格里边
            // 先拿到运营数据
            String reportData = (String) result.get("reportData");
            Integer todayNewMember = (Integer) result.get("todayNewMember");
            Integer totalMember = (Integer) result.get("totalMember");
            Integer thisWeekNewMember = (Integer) result.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) result.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) result.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) result.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) result.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) result.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) result.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) result.get("thisMonthVisitsNumber");
            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) result.get("hotSetmeal");

            // 获取模板文件的绝对路径
            String filePath = request.getSession().getServletContext().getRealPath("template")+ File.separator+"report_template.xlsx";

            // 获取工作薄读取到内存
            Workbook workbook = new XSSFWorkbook(new FileInputStream(new File(filePath)));
            // 获取工作薄中的第一章表
            Sheet sheet = workbook.getSheetAt(0);
            // 依次设置数据
            Row row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportData);

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);//新增会员数（本日）
            row.getCell(7).setCellValue(totalMember);//总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for (Map<String, Object> map : hotSetmeal) {
                String name = (String) map.get("name");
                Long setmeal_count = (Long) map.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }

            // 利用response对象将表格文件响应给浏览器
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            workbook.write(out);

            // 刷新并关闭资源
            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request,HttpServletResponse response){
        try {
            Map<String, Object> result = reportService.getBusinessReportData();

            List<Map> hotSetmeal = (List<Map>) result.get("hotSetmeal");
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            // 编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            // 填充数据
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, result, new JRBeanCollectionDataSource(hotSetmeal));

            // 向客户端传输数据
            OutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition","attachment;filename=report.pdf");

            // 导出数据
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }
    @RequestMapping("/getMemberReportByDate")
    public Result getMemberReportByDate(@RequestBody Map map){
        try {
            Map result=  memberService.getMemberReportByDate(map);
            return  new Result( true,MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,result);
        }catch (Exception e){
            e.printStackTrace();
            return  new Result( false,MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }


}
